package com.stek.camera;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.FrameLayout;

import com.google.android.gms.ads.AdView;
import com.stek.R;
import com.stek.base.BaseOverLayActivity;
import com.stek.utils.AdMode;
import com.stek.utils.Logging;
import com.stek.utils.Utils;

public class MirrorActivity extends BaseOverLayActivity {
	private Camera mCamera;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mirror);
		mCamera = Utils.CameraHardware.getFrontCamera();
		if (mCamera != null) {
			((FrameLayout) findViewById(R.id.frame)).addView(new CameraPreview(
					getApplicationContext(), mCamera));
		}
		adView = (AdView) findViewById(R.id.admod);
		AdMode.init(adView);
	}

	@Override
	protected void initActionBar() {
		super.initActionBar();
		getSupportActionBar().setDisplayHomeAsUpEnabled(false);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		getSupportActionBar()
				.setBackgroundDrawable(
						new ColorDrawable(getResources().getColor(
								R.color.transparent)));

	}

	@Override
	protected void onPause() {
		Utils.CameraHardware.releaseCamera(mCamera);
		finish();
		super.onPause();
	}

	// ===============================================================
	private static class CameraPreview extends SurfaceView implements
			SurfaceHolder.Callback {
		private SurfaceHolder mHolder;
		private Camera mCamera;

		@SuppressWarnings("deprecation")
		public CameraPreview(Context context, Camera camera) {
			super(context);
			mCamera = camera;
			mHolder = getHolder();
			mHolder.addCallback(this);
			mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}

		public void surfaceCreated(SurfaceHolder holder) {
			try {
				mCamera.setPreviewDisplay(holder);
				mCamera.setDisplayOrientation(90);
				mCamera.startPreview();
			} catch (Exception e) {
			}
		}

		public void surfaceDestroyed(SurfaceHolder holder) {
		}

		public void surfaceChanged(SurfaceHolder holder, int format, int w,
				int h) {
			if (mHolder.getSurface() == null) {
				return;
			}
			try {
				mCamera.stopPreview();
			} catch (Exception e) {
				Logging.log(e);
			}
			try {
				mCamera.setPreviewDisplay(mHolder);
				mCamera.startPreview();

			} catch (Exception e) {
			}
		}
	}
}
